package com.dms.modules.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.cart.entity.CartItem;
import com.dms.modules.cart.mapper.CartMapper;
import com.dms.modules.cart.service.CartService;
import com.dms.modules.cart.dto.CartItemDTO;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductSku;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.service.ProductSkuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;
import com.google.gson.Gson;
import java.util.Set;

@Slf4j
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, CartItem> implements CartService {

    private final ProductService productService;
    private final ProductSkuService productSkuService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addToCart(Long userId, Long productId, Long skuId, Integer quantity) {
        // 查询商品
        Product product = productService.getById(productId);
        if (product == null || !product.getStatus().equals(1)) {
            throw new BusinessException("商品不存在或已下架");
        }
        Long merchantId = product.getMerchantId();

        // 验证SKU
        ProductSku sku = null;
        BigDecimal price;
        String specValues;
        
        if (skuId != null) {
            // 有规格商品
            sku = productSkuService.getById(skuId);
            if (sku == null || !sku.getStatus().equals(1)) {
                throw new BusinessException("商品规格不存在或已下架");
            }
            if (!sku.getProductId().equals(productId)) {
                throw new BusinessException("商品规格信息不匹配");
            }
            if (sku.getStock() < quantity) {
                throw new BusinessException("商品库存不足");
            }
            price = sku.getPrice();
            specValues = sku.getSpecValues();
        } else {
            // 无规格商品
            if (product.getStock() < quantity) {
                throw new BusinessException("商品库存不足");
            }
            price = product.getPrice();
            specValues = "{}"; // 空规格JSON
        }

        // 查找购物车中是否已存在该商品
        LambdaQueryWrapper<CartItem> wrapper = new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId)
                .eq(CartItem::getMerchantId, merchantId)
                .eq(CartItem::getProductId, productId);
        
        // 对于无规格商品，不需要考虑skuId
        if (skuId != null) {
            wrapper.eq(CartItem::getSkuId, skuId);
        } else {
            wrapper.isNull(CartItem::getSkuId);
        }

        CartItem existingItem = getOne(wrapper);

        if (existingItem != null) {
            // 检查库存是否足够
            int newQuantity = existingItem.getQuantity() + quantity;
            if (skuId != null) {
                if (sku.getStock() < newQuantity) {
                    throw new BusinessException("商品库存不足");
                }
            } else {
                if (product.getStock() < newQuantity) {
                    throw new BusinessException("商品库存不足");
                }
            }
            
            existingItem.setQuantity(newQuantity);
            existingItem.setTotalPrice(price.multiply(new BigDecimal(newQuantity)));
            existingItem.setStatus(0);
            existingItem.setAllocatedStock(newQuantity);
            updateById(existingItem);
        } else {
            CartItem cartItem = new CartItem();
            cartItem.setUserId(userId);
            cartItem.setMerchantId(merchantId);
            cartItem.setProductId(productId);
            cartItem.setSkuId(skuId);
            cartItem.setProductName(product.getName());
            cartItem.setProductImg(product.getMainImage());
            cartItem.setSpecInfo(specValues);
            cartItem.setPrice(price);
            cartItem.setQuantity(quantity);
            cartItem.setTotalPrice(price.multiply(new BigDecimal(quantity)));
            cartItem.setStatus(0);
            cartItem.setAllocatedStock(quantity);
            save(cartItem);
        }

        // 预分配库存
        if (skuId != null) {
            productSkuService.allocateStock(skuId, quantity);
        } else {
            // 更新商品总库存
            product.setStock(product.getStock() - quantity);
            productService.updateById(product);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQuantity(Long userId, Long cartItemId, Integer quantity) {
        // 1. 验证购物车项是否存在且属于当前用户
        CartItem cartItem = getById(cartItemId);
        if (cartItem == null || !cartItem.getUserId().equals(userId)) {
            throw new BusinessException("购物车项不存在");
        }

        try {
            // 2. 检查库存
            if (cartItem.getSkuId() != null) {
                // 有SKU的商品，检查SKU库存
                ProductSku sku = productSkuService.getById(cartItem.getSkuId());
                if (sku == null || !sku.getStatus().equals(1)) {
                    throw new BusinessException("商品规格不存在或已下架");
                }
                if (sku.getStock() < quantity) {
                    throw new BusinessException("商品库存不足");
                }
            } else {
                // 无SKU的商品，直接检查商品库存
                Product product = productService.getById(cartItem.getProductId());
                if (product == null || !product.getStatus().equals(1)) {
                    throw new BusinessException("商品不存在或已下架");
                }
                if (product.getStock() < quantity) {
                    throw new BusinessException("商品库存不足");
                }
            }

            // 3. 计算库存差值
            int stockDiff = quantity - cartItem.getQuantity();

            // 4. 更新购物车项
            cartItem.setQuantity(quantity);
            cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(quantity)));
            cartItem.setStatus(0); // 重置状态为正常
            cartItem.setAllocatedStock(quantity); // 更新预分配库存
            updateById(cartItem);

            // 5. 更新库存
            if (stockDiff != 0) {
                if (cartItem.getSkuId() != null) {
                    // 更新SKU库存
                    productSkuService.allocateStock(cartItem.getSkuId(), stockDiff);
                } else {
                    // 更新商品库存
                    Product product = productService.getById(cartItem.getProductId());
                    product.setStock(product.getStock() - stockDiff);
                    productService.updateById(product);
                }
            }

            log.info("更新购物车商品数量成功: userId={}, cartItemId={}, quantity={}", 
                    userId, cartItemId, quantity);
        } catch (Exception e) {
            log.error("更新购物车商品数量失败: userId={}, cartItemId={}, quantity={}, error={}", 
                    userId, cartItemId, quantity, e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 从购物车移除商品
     * @param userId 用户ID
     * @param cartItemIds 购物车项ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeFromCart(Long userId, List<Long> cartItemIds) {
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            return;
        }

        try {
            // 查询所有要删除的购物车项
            List<CartItem> cartItems = listByIds(cartItemIds);
            if (cartItems.isEmpty()) {
                return;
            }

            // 验证所有购物车项是否属于当前用户
            for (CartItem cartItem : cartItems) {
                if (!cartItem.getUserId().equals(userId)) {
                    throw new BusinessException("购物车项不属于当前用户");
                }
            }

            // 释放所有预分配的库存
            for (CartItem cartItem : cartItems) {
                if (cartItem.getAllocatedStock() > 0) {
                    if (cartItem.getSkuId() != null) {
                        // 有SKU的商品，释放SKU库存
                        productSkuService.releaseStock(cartItem.getSkuId(), cartItem.getAllocatedStock());
                    } else {
                        // 无SKU的商品，直接更新商品库存
                        Product product = productService.getById(cartItem.getProductId());
                        if (product != null) {
                            product.setStock(product.getStock() + cartItem.getAllocatedStock());
                            productService.updateById(product);
                        }
                    }
                }
            }

            // 批量删除购物车项
            removeByIds(cartItemIds);
        } catch (Exception e) {
            log.error("删除购物车项失败: userId={}, cartItemIds={}", userId, cartItemIds, e);
            throw new BusinessException("删除购物车项失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearCart(Long userId) {
        List<CartItem> cartItems = list(new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId));

        // 释放所有预分配库存
        for (CartItem item : cartItems) {
            if (item.getAllocatedStock() > 0) {
                productSkuService.releaseStock(item.getSkuId(), item.getAllocatedStock());
            }
        }

        // 删除购物车项
        remove(new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId));
    }

    @Override
    public List<CartItemDTO> getUserCartItems(Long userId) {
        // 获取购物车列表
        List<CartItem> cartItems = list(new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId)
                .orderByDesc(CartItem::getCreateTime));

        // 转换为DTO
        return cartItems.stream()
                .map(item -> {
                    CartItemDTO dto = new CartItemDTO();
                    dto.setId(item.getId());
                    dto.setProductId(item.getProductId());
                    dto.setSkuId(item.getSkuId());
                    dto.setMerchantId(item.getMerchantId());
                    dto.setProductName(item.getProductName());
                    dto.setProductImg(item.getProductImg());
                    dto.setSpecInfo(item.getSpecInfo());
                    dto.setPrice(item.getPrice());
                    dto.setQuantity(item.getQuantity());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Map<Long, List<CartItemDTO>> getUserCartItemsByMerchant(Long userId) {
        List<CartItemDTO> cartItems = getUserCartItems(userId);
        return cartItems.stream()
                .collect(Collectors.groupingBy(CartItemDTO::getMerchantId));
    }

    @Override
    public IPage<CartItem> getCartPage(Page<CartItem> page, Long userId) {
        return page(page, new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId)
                .orderByDesc(CartItem::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCartItemsStatus() {
        // 获取所有购物车项
        List<CartItem> cartItems = list();
        if (cartItems.isEmpty()) {
            return;
        }

        // 按SKU ID分组
        Map<Long, List<CartItem>> skuGroups = cartItems.stream()
                .collect(Collectors.groupingBy(CartItem::getSkuId));

        // 批量更新状态
        for (Map.Entry<Long, List<CartItem>> entry : skuGroups.entrySet()) {
            Long skuId = entry.getKey();
            List<CartItem> items = entry.getValue();

            ProductSku sku = productSkuService.getById(skuId);
            if (sku == null || !sku.getStatus().equals(1)) {
                // SKU不存在或已下架
                updateItemsStatus(items, 1);
                continue;
            }

            // 检查库存
            if (sku.getStock() < items.stream().mapToInt(CartItem::getQuantity).sum()) {
                updateItemsStatus(items, 2);
                continue;
            }

            // 检查价格变动
            for (CartItem item : items) {
                if (!item.getPrice().equals(sku.getPrice())) {
                    item.setStatus(3);
                    item.setPrice(sku.getPrice());
                    item.setTotalPrice(sku.getPrice().multiply(new BigDecimal(item.getQuantity())));
                    updateById(item);
                }
            }
        }
    }

    private void updateItemsStatus(List<CartItem> items, Integer status) {
        for (CartItem item : items) {
            item.setStatus(status);
            updateById(item);
        }
    }
} 